/**
 * @FileName: Params.java
 * @Author
 * @Description:
 * @Date 2017年1月10日 下午3:57:12
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.util;

import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.StrKit;

import cn.hpclub.server.constant.ClientApiConstant;

/**
 * 对加密后参数串进行解析和获取。key=value&key=value&key=value，其中value已做urlencode。
 * ，origin=&timestamp=&v=&digest=&appkey=&token=不进行加密
 */
public class Params{
    public static final String                DES         = "DES";
    private static final Logger               logger      = LoggerFactory.getLogger(Params.class);
    private static final String               ENCODE_UTF8 = "UTF-8";
    private ConcurrentHashMap<String, String> map         = new ConcurrentHashMap<String, String>();

    public Params(String params){
        // logger.info("class params = " + params);
        parseMap(params);
    }

    public Params(String method, String paramsBefore){
        if(!method.equals(DES)){
            // 不解析，后续获取什么key的value都会为空
            return;
        }
        // logger.info("class desc params = " + paramsBefore);
        String params = null;
        try{
            params = DESCrypto.decrypt(paramsBefore, ClientApiConstant.CONSTANT_DES_KEY);
            parseMap(params);
        }
        catch(Exception e){
            logger.error("class params des decode error.origin params:" + paramsBefore);
            e.printStackTrace();
        }

    }

    public String getPara(String key){
        return map.get(key);
    }

    public int getParaToInt(String key, int dValue){
        String value = map.get(key);
        int iValue = dValue;
        try{
            iValue = Integer.valueOf(value);
        }
        catch(Exception e){
            logger.error("getParaToInt exception:" + key + ":" + value);
            iValue = dValue;
        }
        return iValue;

    }

    /**
     * @Title: parseMap
     * @Description:TODO
     * @param params
     *            void
     */

    private void parseMap(String params){
        if(StrKit.isBlank(params)){
            // 直接退出去，空map后续什么也获取不到
            logger.warn("params  is blank.");
            return;
        }

        String[] array = params.split("&");
        for(int i = 0; i < array.length; i++){
            String keyValue = array[i];
            // logger.info(keyValue);
            if(StrKit.isBlank(keyValue)){
                // 跳过
                logger.warn("keyValue is blank:" + keyValue);
                continue;
            }
            String[] keyValueArray = keyValue.split("=");
            String keyString = "";
            String valueString = "";
            if(keyValueArray.length > 0){
                keyString = keyValueArray[0];
            } else{
                // 非法数据，跳过
                logger.warn("keyValue is ilegal:" + keyValue + ":" + keyValueArray.length);
                continue;
            }

            if(keyValueArray.length == 1){
                // a=这种情况
                valueString = "";
            } else if(keyValueArray.length == 2){
                // a=x这种情况
                valueString = urlDecode(keyValueArray[1]);
            } else{
                // 其他情况 a=x=y，跳过
                logger.warn("keyValue is not ilegal:" + keyValue);
                continue;
            }
            map.put(keyString, valueString);
        }
        // 调试
        // System.out.println("param str:");
        // for(Iterator iter = map.keySet().iterator(); iter.hasNext();){
        // String name = (String)iter.next();
        // String values = map.get(name);
        //
        // System.out.print(name + "=" + values + "&");
        //
        // }
        // System.out.println("");
        // System.out.println("param str end");
    }

    String urlDecode(String valueBefore){
        String value = "";
        try{
            value = java.net.URLDecoder.decode(valueBefore, ENCODE_UTF8);
        }
        catch(Exception e){
            value = "";
            logger.error("decode error,orginal params:" + valueBefore);
            logger.error("class url decode error:" + valueBefore);
            e.printStackTrace();
        }
        return value;
    }

}
